package com.fanketly.funacg2.ui.screen

import android.util.Log
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.paging.rememberLazyListState
import com.fanketly.funacg2.ui.components.HomeListCard
import com.fanketly.funacg2.ui.theme.dp8
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.ui.viewmodels.TagViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.launch

@Destination
@Composable
fun ShowThisTagScreen(
    tag: Int,
    tagViewModel: TagViewModel = hiltViewModel(),
    homeViewModel: HomeViewModel,
    navigator: DestinationsNavigator,
) {

    LaunchedEffect(key1 = Unit, block = {
        if (homeViewModel.isFirstToShowThisTagScreen) {
            Log.i(TAG, "ShowThisTagScreen_tag:$tag")
            homeViewModel.isFirstToShowThisTagScreen = false
            tagViewModel.tag = tag
        }
    })
    BackHandler {
        navigator.navigateUp()
    }
    val lazyPagingItems = tagViewModel.showThisTagPager.collectAsLazyPagingItems()
    val lazyListState = lazyPagingItems.rememberLazyListState()
//    LaunchedEffect(key1 = lazyListState.firstVisibleItemIndex, block = {
//        Log.i(
//            TAG,
//            "ShowThisTagScreen_firstVisibleItemIndex: ${lazyListState.firstVisibleItemIndex}"
//        )
//    })
//    val lazyListState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()
    LaunchedEffect(key1 = lazyPagingItems.loadState, block = {
        if (lazyPagingItems.loadState.refresh == LoadState.Loading) {
            lazyListState.scrollToItem(0)
        }
        Log.i(
            TAG,
            "ShowThisTagScreen_loadState: ${lazyPagingItems.loadState.source}"
        )
    })
    Box(Modifier.fillMaxSize()) {
        ShowThisTagCardList(lazyPagingItems, lazyListState, onTagClick = {
            // TODO: 还可以优化
            coroutineScope.launch {
                if (tagViewModel.tag != it) {
                    tagViewModel.tag = it
                    lazyPagingItems.refresh()
                }
//                if (tagViewModel.setTag(it)) {
//                    Log.i(TAG, "ShowThisTagScreen_onTagClick:$it ")
//
//                }
            }
        }, homeViewModel::getAudio)
    }

}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShowThisTagCardList(
    lazyPagingItems: LazyPagingItems<WorkList.Work>,
    lazyListState: LazyListState,
    onTagClick: (tag: Int) -> Unit,
    getAudio: (WorkList.Work) -> Unit,
) {
//    if (lazyPagingItems.itemCount == 0) {
//        //endOfPaginationReached-如果LoadState关联的LoadType中有更多数据要加载，则为false，否则为true。此参数通知Pager是否应继续向该方向请求其他数据，或是否应在数据集结束时停止。
//        if (lazyPagingItems.loadState.source.prepend != LoadState.NotLoading(false)) {
//            Text(text = "没有数据")
//        } else {
//            Text(text = "正在加载中..")
//        }
    if (lazyPagingItems.loadState.refresh == LoadState.Loading) {
        LinearProgressIndicator(
            modifier = Modifier.fillMaxWidth()
        )
    } else LazyColumn(
        modifier = Modifier.fillMaxSize(),
        state = lazyListState,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        items(lazyPagingItems.itemCount, key = lazyPagingItems.itemKey { it.id }) { index ->
            val work = lazyPagingItems[index]
            if (work == null) {
                ElevatedCard(
                    onClick = {},
                    modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .height(300.dp)
                        .padding(top = dp8, bottom = dp8),
                ) {}
            } else {
                HomeListCard(work, onTagClick = onTagClick) {
                    getAudio(work)
                }
            }
        }
        if (lazyPagingItems.loadState.append == LoadState.Loading) {
            item {
                CircularProgressIndicator(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentWidth(Alignment.CenterHorizontally)
                )
            }
        }
    }
}

@Composable
fun ShowScreenContent() {

}
